import { Response } from 'express';
import { AuthenticatedRequest } from '../types/auth';
import prisma from '../lib/prisma';
import { ApiError } from '../utils/ApiError';
import { StatusCodes } from '../constants/statusCodes';
import { logger } from '../utils/logger';

export const teachingPointController = {
  // 创建教学点
  async createTeachingPoint(req: AuthenticatedRequest, res: Response) {
    try {
      if (!req.user) {
        throw new ApiError(StatusCodes.UNAUTHORIZED, '未授权访问');
      }

      const {
        name,
        code,
        address,
        type,
        capacity,
        status,
        principal,
        contact,
        description,
        facilities
      } = req.body;

      const existingPoint = await prisma.teachingPoint.findUnique({
        where: { code }
      });

      if (existingPoint) {
        throw new ApiError(StatusCodes.CONFLICT, '教学点代码已存在');
      }

      const teachingPoint = await prisma.teachingPoint.create({
        data: {
          name,
          code,
          address,
          type,
          capacity,
          status,
          principal,
          contact,
          description,
          facilities,
          creatorId: req.user.id
        }
      });

      logger.info('Created teaching point', { teachingPointId: teachingPoint.id });
      res.status(StatusCodes.CREATED).json(teachingPoint);
    } catch (error) {
      logger.error('Error creating teaching point', { error });
      throw error;
    }
  },

  // 获取教学点列表
  async getTeachingPoints(req: AuthenticatedRequest, res: Response) {
    try {
      const { type, status, search } = req.query;
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;

      const where = {
        deleted: false,
        ...(type && { type: String(type) }),
        ...(status && { status: String(status) }),
        ...(search && {
          OR: [
            { name: { contains: String(search), mode: 'insensitive' } },
            { code: { contains: String(search), mode: 'insensitive' } },
            { address: { contains: String(search), mode: 'insensitive' } }
          ]
        })
      };

      const [teachingPoints, total] = await prisma.$transaction([
        prisma.teachingPoint.findMany({
          where,
          skip: (page - 1) * limit,
          take: limit,
          orderBy: { createdAt: 'desc' }
        }),
        prisma.teachingPoint.count({ where })
      ]);

      res.json({
        items: teachingPoints,
        total,
        page,
        pages: Math.ceil(total / limit)
      });
    } catch (error) {
      logger.error('Error getting teaching points', { error });
      throw error;
    }
  },

  // 获取教学点详情
  async getTeachingPointById(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;

      const teachingPoint = await prisma.teachingPoint.findFirst({
        where: { id, deleted: false }
      });

      if (!teachingPoint) {
        throw new ApiError(StatusCodes.NOT_FOUND, '教学点不存在');
      }

      res.json(teachingPoint);
    } catch (error) {
      logger.error('Error getting teaching point', { error });
      throw error;
    }
  },

  // 更新教学点
  async updateTeachingPoint(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;
      const updates = req.body;

      if (updates.code) {
        const existingPoint = await prisma.teachingPoint.findFirst({
          where: {
            code: updates.code,
            id: { not: id },
            deleted: false
          }
        });

        if (existingPoint) {
          throw new ApiError(StatusCodes.CONFLICT, '教学点代码已存在');
        }
      }

      const teachingPoint = await prisma.teachingPoint.update({
        where: { id },
        data: updates
      });

      logger.info('Updated teaching point', { teachingPointId: id });
      res.json(teachingPoint);
    } catch (error) {
      logger.error('Error updating teaching point', { error });
      throw error;
    }
  },

  // 删除教学点（软删除）
  async deleteTeachingPoint(req: AuthenticatedRequest, res: Response) {
    try {
      const { id } = req.params;

      await prisma.teachingPoint.update({
        where: { id },
        data: {
          deleted: true,
          deletedAt: new Date()
        }
      });

      logger.info('Deleted teaching point', { teachingPointId: id });
      res.status(StatusCodes.NO_CONTENT).send();
    } catch (error) {
      logger.error('Error deleting teaching point', { error });
      throw error;
    }
  },

  // 批量更新教学点状态
  async batchUpdateStatus(req: AuthenticatedRequest, res: Response) {
    try {
      const { ids, status } = req.body;

      await prisma.$transaction(
        ids.map((id: string) =>
          prisma.teachingPoint.update({
            where: { id },
            data: { status }
          })
        )
      );

      logger.info('Batch updated teaching points status', { ids, status });
      res.json({ message: '批量更新状态成功' });
    } catch (error) {
      logger.error('Error batch updating teaching points status', { error });
      throw error;
    }
  }
};
